<template>
  <div class="p-3">
    <a-card style="height: 820px" :bordered="false">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="归属机构">
          <a-tree-select
            v-model:value="searchForm.belongComId"
            tree-node-filter-prop="label"
            style="width: 150px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
        </a-form-item>
        <a-form-item label="通知类型">
          <a-select
            style="width: 150px"
            placeholder="请选择通知类型"
            v-model="searchForm.noticeType"
          />
        </a-form-item>
        <a-form-item label="发布状态">
          <a-select
            style="width: 150px"
            placeholder="请选择发布状态"
            v-model="searchForm.status"
          />
        </a-form-item>
        <a-form-item label="发布人">
          <a-select
            style="width: 150px"
            placeholder="请选择发布人"
            v-model="searchForm.createPersonId"
          />
        </a-form-item>
        <a-form-item label="模版类型">
          <a-select style="width: 150px" placeholder="请选择模版类型" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary">重置</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="showAddModal">新增</a-button>
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        bordered
        :pagination="pagination"
        class="mt-5"
        :scroll="{ y: 600 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag
              :bordered="false"
              v-if="record.status == '0'"
              color="processing"
              >审批中</a-tag
            >
            <a-tag :bordered="false" v-if="record.status == '1'" color="success"
              >同意</a-tag
            >
            <a-tag :bordered="false" v-if="record.status == '2'" color="error"
              >拒绝</a-tag
            >
          </template>
          <template v-if="column.dataIndex === 'visibleComName'">
            {{
              record.visibleComName.length > 0
                ? record.visibleComName.join(',')
                : '暂无'
            }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <!-- <a-button type="link">查看</a-button> -->

            <a-button type="link" @click="showEditModal(record)">编辑</a-button>
            <a-popconfirm
              placement="bottom"
              ok-text="是"
              cancel-text="否"
              title="确认删除吗？"
              @confirm="handleDelete(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑通知弹窗 -->
    <a-modal
      :visible="addModalVisible"
      :title="isEdit ? '编辑通知' : '发布通知'"
      width="800px"
      @ok="handleAddSubmit"
      @cancel="handleAddCancel"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item label="归属机构" name="belongComId">
          <a-tree-select
            v-model:value="addForm.belongComId"
            tree-node-filter-prop="label"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
        </a-form-item>

        <a-form-item label="通知标题" name="noticeName">
          <a-input
            v-model:value="addForm.noticeName"
            placeholder="请输入通知标题"
          />
        </a-form-item>

        <a-form-item label="通知类型" name="noticeType">
          <a-input
            v-model:value="addForm.noticeType"
            placeholder="请选择通知类型"
          />
        </a-form-item>

        <a-form-item label="可见范围" name="visibleComId">
          <a-tree-select
            v-model:value="addForm.visibleComId"
            :tree-data="comanyList"
            tree-checkable
            allow-clear
            placeholder="请选择子公司"
            :max-tag-count="2"
          />
        </a-form-item>

        <a-form-item label="发布人" name="createPersonName">
          <a-input
            v-model:value="addForm.createPersonName"
            placeholder="请输入发布人"
          />
        </a-form-item>

        <!-- <a-form-item label="模版类型" name="templateType">
          <a-select v-model="addForm.templateType" placeholder="请选择模版类型">
            <a-select-option value="普通">普通</a-select-option>
            <a-select-option value="紧急">紧急</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="模版名称" name="templateName">
          <a-input
            v-model="addForm.templateName"
            placeholder="请输入模版名称"
          />
        </a-form-item> -->
        <a-form-item label="通知内容" name="noticeContent">
          <UEditor
            v-model="addForm.noticeContent"
            :height="300"
            width="100%"
            placeholder="请输入协议内容"
          />
        </a-form-item>
        <a-form-item label="通知附件">
          <a-upload
            v-model:file-list="fileLists"
            :show-upload-list="false"
            name="file"
            action="/api/ChargeSystem/file/uploadAttachment"
            :headers="header"
            :beforeUpload="beforeUploadAttachment"
            accept=".pdf,.doc,.docx,.xls,.xlsx,.png,.jpg"
            @change="handleChanges"
          >
            <a-button type="primary"> 点击上传 </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import {
  getNoticeInfo,
  addNoticeInfo,
  editNoticeInfo,
  delNoticeInfo,
} from '#/api/core/setting';
import { getSubCompanyApi } from '#/api/core/charge';
import UEditor from '#/components/Editor/UEditor.vue';
import { getCompanyTree } from '#/api/core/develop';
import { message } from 'ant-design-vue';
import { useAccessStore } from '@vben/stores';
// // 临时模拟API函数，请根据实际项目路径调整
// const getNoticeInfo = async (query: any) => {
//   console.log('调用getNoticeInfo:', query);
//   return { data: { code: 200, data: [], total: 0 } };
// };
// const addNoticeInfo = async (data: any) => {
//   console.log('调用addNoticeInfo:', data);
//   return { data: { code: 200 } };
// };
// const editNoticeInfo = async (data: any) => {
//   console.log('调用editNoticeInfo:', data);
//   return { data: { code: 200 } };
// };
// const delNoticeInfo = async (data: any) => {
//   console.log('调用delNoticeInfo:', data);
//   return { data: { code: 200 } };
// };
const fileLists = ref([]);
const accessStore = useAccessStore();
const header = {
  Authorization: accessStore.accessToken || localStorage.getItem('token'),
};
interface TreeNode {
  value: string;
  id: string;
  level: string;
  label: string;
  children?: TreeNode[];
}
const companyOptions = ref<TreeNode[]>([]);
const searchForm = reactive({
  belongComId: undefined,
  noticeType: undefined,
  status: undefined,
  createPersonId: undefined,
});
const columns = [
  {
    title: '归属机构',
    dataIndex: 'belongComName',
    key: 'belongComName',
    align: 'center',
  },
  {
    title: '通知标题',
    dataIndex: 'noticeName',
    key: 'noticeName',
    align: 'center',
  },
  {
    title: '通知类型',
    dataIndex: 'noticeType',
    key: 'noticeType',
    align: 'center',
  },
  {
    title: '可见范围',
    dataIndex: 'visibleComName',
    key: 'visibleComName',
    align: 'center',
  },
  {
    title: '申请时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
  },
  {
    title: '发布人',
    dataIndex: 'createPersonName',
    key: 'createPersonName',
    align: 'center',
  },
  {
    title: '发布状态',
    dataIndex: 'status',
    key: 'status',
    align: 'center',
  },
  {
    title: '最后更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
  },
];
const dataSource = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});

// 新增/编辑弹窗相关
const addModalVisible = ref(false);
const addFormRef = ref();
const isEdit = ref(false);
const editingRecord = ref<any>(null);
const addForm = reactive({
  belongComId: '',
  noticeName: '',
  noticeType: '',
  noticeContent: '',
  visibleComId: undefined,
  createPersonId: '',
  attachmentUrl: '',
  createPersonName: '',
});
const comanyList = ref([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      // console.log(tree)
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    // console.log(comanyList.value);
  });
};
getTableData();
// 显示新增弹窗
const showAddModal = () => {
  isEdit.value = false;
  editingRecord.value = null;
  addModalVisible.value = true;
};

// 显示编辑弹窗
const showEditModal = (record: any) => {
  isEdit.value = true;
  editingRecord.value = record;
  // 将记录数据填充到表单中
  Object.assign(addForm, {
    belongComId: record.belongComId || '',
    noticeName: record.noticeName || '',
    noticeType: record.noticeType || '',
    noticeContent: record.noticeContent || '',
    visibleComId: record.visibleComId || '',
    createPersonName: record.createPersonName || '',
    createPersonId: record.createPersonId || '',
    attachmentUrl: record.attachmentUrl || '',
  });
  addModalVisible.value = true;
};

// 处理新增/编辑提交
const handleAddSubmit = async () => {
  try {
    await addFormRef.value.validate();
    console.log('提交数据:', addForm);

    if (isEdit.value) {
      // 编辑模式，调用编辑接口
      const editData = {
        ...addForm,
        id: editingRecord.value?.id || '', // 添加记录ID
      };
      const res = await editNoticeInfo(editData);
      if (res?.data?.code === 200) {
        console.log('编辑成功');
        onSearch(); // 刷新列表
      } else {
        message.error(res?.data?.msg);
      }
    } else {
      console.log(addForm);
      // 新增模式，调用新增接口
      const res = await addNoticeInfo(addForm);
      if (res?.data?.code === 200) {
        console.log('新增成功');
        onSearch(); // 刷新列表
      }
    }

    addModalVisible.value = false;
    resetAddForm();
  } catch (error) {
    console.log('验证失败:', error);
  }
};

// 处理新增/编辑取消
const handleAddCancel = () => {
  addModalVisible.value = false;
  resetAddForm();
};

// 重置表单
const resetAddForm = () => {
  isEdit.value = false;
  editingRecord.value = null;
  (Object.keys(addForm) as Array<keyof typeof addForm>).forEach((key) => {
    addForm[key] = '';
  });
  addFormRef.value?.resetFields();
};

// 处理删除
const handleDelete = async (record: any) => {
  try {
    const res = await delNoticeInfo({ id: record.id });
    if (res?.data?.code === 200) {
      console.log('删除成功');
      onSearch(); // 刷新列表
    }
  } catch (error) {
    console.log('删除失败:', error);
  }
};

// 自定义上传处理
const customRequest = (options: any) => {
  // 这里可以实现文件上传逻辑
  console.log('上传文件:', options);
};
const onSearch = () => {
  const query = {
    belongComId: searchForm.belongComId ?? [],
    noticeType: searchForm.noticeType ?? '',
    status: searchForm.status ?? null,
    createPersonId: searchForm.createPersonId ?? null,
    page: pagination.current,
    limit: pagination.pageSize,
  };
  getNoticeInfo(query).then((res: any) => {
    console.log(res);
    if (res?.data?.code === 200) {
      dataSource.value = res.data.data || [];
      pagination.total = res.data.total || 0;
    }
  });
};
const beforeUploadAttachment = (file: File) => {
  const isPdf = file.type === 'application/pdf';
  const isDoc = file.type === 'application/msword';
  const isDocx =
    file.type ===
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  const isXls = file.type === 'application/vnd.ms-excel';
  const isXlsx =
    file.type ===
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isPng = file.type === 'image/png';
  const isJpg = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  const isSupportedFormat =
    isPdf || isDoc || isDocx || isXls || isXlsx || isPng || isJpg;

  if (!isSupportedFormat) {
    message.error('仅支持pdf/doc/docx/xls/xlsx/png/jpg格式文件!');
  }
  if (!isLt2M) {
    message.error('文件大小限制2MB以内!');
  }
  return isSupportedFormat && isLt2M;
};
const handleChanges = (info: any) => {
  console.log(info);
  if (info.file.status === 'done') {
    if (info.file.response && info.file.response.code === 200) {
      message.success(`${info.file.name} 文件上传成功`);
      addForm.attachmentUrl = info.file.response.msg;
    } else {
      message.error(
        `${info.file.name} 文件上传失败: ${info.file.response ? info.file.response.message : '未知错误'}`,
      );
    }
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`);
  }
};
</script>
<style scoped></style>
